from rest_framework import serializers

from library_app.models import Category, Book, Author

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = "__all__"

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = "__all__"

class BookReadSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    author = AuthorSerializer()

    class Meta:
        model = Book
        fields = '__all__'

class BookWriteSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    author = AuthorSerializer()
    
    class Meta:
        model = Book
        fields = "__all__"
    
    def create(self, validated_data):
        category = validated_data.pop('category')
        category_obj = Category.objects.get(title=category['title'])
        author = validated_data.pop('author')
        author_obj = Author.objects.get(name=author['name'])
        return Book.objects.create(category=category_obj, author=author_obj, **validated_data)
    
    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.owned = validated_data.get('owned', instance.owned)
        instance.price = validated_data.get('price', instance.price)
        instance.publish_date = validated_data.get('publish_date', instance.publish_date)
        author = validated_data.pop('author')
        instance.author = Author.objects.get(name=author['name'])
        category = validated_data.pop('category')
        instance.category = Category.objects.get(title=category['title'])
        instance.save()
        return instance
